package com.example.mediamoudle.widget

import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.SeekBar
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.example.mediamoudle.R
import com.example.mediamoudle.recycle.utils.TimeFormater

class SeekBarPictureView @JvmOverloads constructor(context: Context,attributeSet: AttributeSet?=null,defaultIndex:Int = 0)
    :ConstraintLayout(context,attributeSet,defaultIndex) {
      private var imageView:ImageView
      private var seekBar:SeekBar
      private var mVideoUrl:String?=null
      private var mDuration:Int = 0
      private var startTimeView:TextView
      private var endTimeView:TextView
      private var mSeekBarProgressChange:((progress:Int)->Unit)?=null
        init {
             imageView = ImageView(getContext()).apply {
                layoutParams = LayoutParams(dp2px(90),dp2px(115)).
                apply {
                    topToTop = LayoutParams.PARENT_ID
                    startToStart = LayoutParams.PARENT_ID
                    endToEnd = LayoutParams.PARENT_ID
                }
            }
            imageView.id = generateViewId()

            val viewLine = View(context).apply {
                layoutParams = LayoutParams(dp2px(1),dp2px(14)).apply {
                    topToBottom = imageView.id
                    startToStart = imageView.id
                    endToEnd = imageView.id
                    topMargin = dp2px(17)
                }
            }
            viewLine.id = generateViewId()
            viewLine.setBackgroundColor(Color.parseColor("#5CD8D8D8"))

             startTimeView = TextView(getContext()).apply {
                layoutParams = LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT).apply {
                    endToStart = viewLine.id
                    topToTop = viewLine.id
                    bottomToBottom = viewLine.id
                    rightMargin = dp2px(8)
                }
            }
            startTimeView.textSize = 18f
            startTimeView.setTextColor(Color.WHITE)
            startTimeView.text = "01:45"

            endTimeView = TextView(getContext()).apply {
                layoutParams = LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT).apply {
                    startToEnd = viewLine.id
                    topToTop = viewLine.id
                    bottomToBottom = viewLine.id
                    leftMargin = dp2px(8)

                }
            }
            endTimeView.setTextColor(Color.GRAY)
            endTimeView.textSize = 18f
            endTimeView.text = "05:00"

            seekBar = SeekBar(getContext()).apply {
                layoutParams = LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,dp2px(24)).apply {
                    topToBottom = viewLine.id
                    startToStart = LayoutParams.PARENT_ID
                    endToEnd = LayoutParams.PARENT_ID
                    leftMargin = dp2px(20)
                    rightMargin = dp2px(20)
                    topMargin =dp2px(24)
                }
            }
            seekBar.thumb = resources.getDrawable(R.drawable.seekbar)
            seekBar.progressDrawable  =resources.getDrawable(R.drawable.minivideo_upload_progress)
            seekBar.max = 100
            seekBar.progress = 50
            addView(imageView)
            addView(viewLine)
            addView(startTimeView)
            addView(endTimeView)
            addView(seekBar)

            seekBar.setOnSeekBarChangeListener(object :SeekBar.OnSeekBarChangeListener{
                override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                    if (fromUser){
                        startTimeView.text = TimeFormater.formatMs(progress.toLong())
                        mVideoUrl?.let { showPreView(it, progress.toLong()) }
                        mSeekBarProgressChange?.let {
                            it.invoke(progress)
                        }

                    }
                }

                override fun onStartTrackingTouch(seekBar: SeekBar?) {
                        imageView.visibility = View.VISIBLE
                    Log.i("TAG321", "onStartTrackingTouch: ")
                }

                override fun onStopTrackingTouch(seekBar: SeekBar) {
                    Log.i("TAG321", "onStopTrackingTouch: ")
                    imageView.visibility = View.GONE
                    postDelayed(
                        {
                         visibility = View.GONE
                        },1000
                    )
                }

            })
        }
    /**
     * 设置视频播放链接URl
     */
    fun setVideoUrl(videoUrl:String){
        this.mVideoUrl = videoUrl
    }

    /**
     * 设置视频总长度
     */
    fun setVideoDuration(duration:Int){
        this.mDuration = duration
        seekBar.max = duration

        endTimeView.text = TimeFormater.formatMs(duration.toLong())
    }
    /**
     * 设置视频当前播放进度
     */
    fun setCurrentDuration(current:Int){
        seekBar.progress = current
        startTimeView.text = TimeFormater.formatMs(current.toLong())

    }

    fun setSeekBarProgressListener(seekBarProgressChange:(progress:Int)->Unit){
        this.mSeekBarProgressChange = seekBarProgressChange
    }


    /**
     * 显示视频某一帧图片
     */
    private fun showPreView(url: String, time: Long) {
        val width =dp2px(90)
        val height = dp2px(115)
        imageView.let {
            Glide.with(context.applicationContext)
                .setDefaultRequestOptions(
                    RequestOptions() //这里限制了只从缓存读取
                        .onlyRetrieveFromCache(true)
                        .frame(1000 * time)
                        .override(width, height)
                        .dontAnimate()
                        .centerCrop()
                )
                .load(url)
                .into(it)
        }
    }

    /**
     * 分辨率转换
     */
    private fun dp2px(dp:Int)= (context.resources.displayMetrics.density*dp+0.5).toInt()

}